package com.waikuai.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.waikuai.shop.dto.ProductDTO;
import com.waikuai.shop.entity.Product;
import com.waikuai.shop.entity.ProductCategory;
import com.waikuai.shop.mapper.ProductMapper;
import com.waikuai.shop.service.ProductService;
import com.waikuai.shop.service.ProductCategoryService;
import com.waikuai.shop.service.UserFavoriteService;
import com.waikuai.shop.vo.ProductDetailVO;
import com.waikuai.shop.vo.ProductSimpleVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品服务实现类
 * @author waikuai
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product>
        implements ProductService {

    private final ProductMapper productMapper;
    private final ProductCategoryService productCategoryService;
    private final UserFavoriteService userFavoriteService;

    @Override
    public IPage<ProductSimpleVO> getProductPage(Page<ProductSimpleVO> page, Long categoryId, String keyword,
                                                 Integer status, Integer isFeatured, String orderBy, String orderType) {
        try {
            // 直接查询并返回VO分页结果，避免类型转换问题
            return productMapper.selectProductPageWithCategory(page, categoryId, keyword, status, isFeatured, orderBy, orderType);
        } catch (Exception e) {
            log.error("分页查询商品列表失败: {}", e.getMessage(), e);
            throw new RuntimeException("分页查询商品列表失败");
        }
    }

    @Override
    public List<ProductSimpleVO> getHotProducts(Integer limit) {
        try {
            List<Product> hotProducts = productMapper.selectHotProducts(limit);
            return hotProducts.stream()
                    .map(this::convertToSimpleVO)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取热门商品失败: {}", e.getMessage(), e);
            return new ArrayList<>();
        }
    }

    @Override
    public List<ProductSimpleVO> getFeaturedProducts(Integer limit) {
        try {
            List<Product> featuredProducts = productMapper.selectFeaturedProducts(limit);
            return featuredProducts.stream()
                    .map(this::convertToSimpleVO)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取推荐商品失败: {}", e.getMessage(), e);
            return new ArrayList<>();
        }
    }

    @Override
    public List<ProductSimpleVO> getNewProducts(Integer limit) {
        try {
            List<Product> newProducts = productMapper.selectNewProducts(limit);
            return newProducts.stream()
                    .map(this::convertToSimpleVO)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取新品商品失败: {}", e.getMessage(), e);
            return new ArrayList<>();
        }
    }

    @Override
    public List<ProductSimpleVO> getProductsByCategoryId(Long categoryId, Integer limit) {
        try {
            List<Product> products = productMapper.selectProductsByCategoryId(categoryId, limit);
            return products.stream()
                    .map(this::convertToSimpleVO)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("根据分类ID获取商品列表失败，分类ID: {}", categoryId, e);
            return new ArrayList<>();
        }
    }

    @Override
    public List<ProductSimpleVO> searchProducts(String keyword, Integer limit) {
        try {
            List<Product> products = productMapper.searchProducts(keyword, limit);
            return products.stream()
                    .map(this::convertToSimpleVO)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("搜索商品失败，关键词: {}", keyword, e);
            return new ArrayList<>();
        }
    }

    @Override
    public ProductDetailVO getProductDetail(Long productId, Long userId) {
        try {
            Product product = productMapper.selectById(productId);
            if (product == null) {
                return null;
            }

            return convertToDetailVO(product, userId);
        } catch (Exception e) {
            log.error("获取商品详情失败，商品ID: {}", productId, e);
            return null;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createProduct(ProductDTO productDTO) {
        try {
            Product product = new Product();
            product.setProductName(productDTO.getProductName());
            product.setCategoryId(productDTO.getCategoryId());
            product.setProductCode(productDTO.getProductCode());
            product.setDescription(productDTO.getDescription());
            // mainImage 优先取 DTO.mainImage；为空则用 images 第一个
            if (productDTO.getMainImage() != null && !productDTO.getMainImage().isEmpty()) {
                product.setMainImage(productDTO.getMainImage());
            } else if (productDTO.getImages() != null && !productDTO.getImages().isEmpty()) {
                product.setMainImage(productDTO.getImages().get(0));
            }

            // 序列化 images 数组为 JSON 字符串
            try {
                if (productDTO.getImages() != null && !productDTO.getImages().isEmpty()) {
                    ObjectMapper mapper = new ObjectMapper();
                    product.setImages(mapper.writeValueAsString(productDTO.getImages()));
                } else {
                    product.setImages(null);
                }
            } catch (JsonProcessingException e) {
                log.warn("序列化商品图片列表失败: {}", e.getMessage());
                product.setImages(null);
            }
            product.setPrice(productDTO.getPrice());
            product.setOriginalPrice(productDTO.getOriginalPrice());
            product.setStockQuantity(productDTO.getStockQuantity());
            product.setMinStock(productDTO.getMinStock());
            product.setStatus(productDTO.getStatus());
            product.setIsFeatured(productDTO.getIsFeatured());
            product.setSalesCount(0);
            product.setViewCount(0);

            int result = productMapper.insert(product);
            if (result > 0) {
                log.info("创建商品成功，商品ID: {}, 商品名称: {}", product.getId(), product.getProductName());
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("创建商品失败: {}", e.getMessage(), e);
            throw new RuntimeException("创建商品失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateProduct(ProductDTO productDTO) {
        try {
            Product product = new Product();
            product.setId(productDTO.getId());
            product.setProductName(productDTO.getProductName());
            product.setCategoryId(productDTO.getCategoryId());
            product.setProductCode(productDTO.getProductCode());
            product.setDescription(productDTO.getDescription());
            // mainImage 优先取 DTO.mainImage；为空则用 images 第一个（如有）
            if (productDTO.getMainImage() != null && !productDTO.getMainImage().isEmpty()) {
                product.setMainImage(productDTO.getMainImage());
            } else if (productDTO.getImages() != null && !productDTO.getImages().isEmpty()) {
                product.setMainImage(productDTO.getImages().get(0));
            }

            // 序列化 images 数组为 JSON 字符串
            try {
                if (productDTO.getImages() != null) {
                    if (!productDTO.getImages().isEmpty()) {
                        ObjectMapper mapper = new ObjectMapper();
                        product.setImages(mapper.writeValueAsString(productDTO.getImages()));
                    } else {
                        product.setImages(null);
                    }
                }
            } catch (JsonProcessingException e) {
                log.warn("序列化商品图片列表失败: {}", e.getMessage());
                product.setImages(null);
            }
            product.setPrice(productDTO.getPrice());
            product.setOriginalPrice(productDTO.getOriginalPrice());
            product.setStockQuantity(productDTO.getStockQuantity());
            product.setMinStock(productDTO.getMinStock());
            product.setStatus(productDTO.getStatus());
            product.setIsFeatured(productDTO.getIsFeatured());

            int result = productMapper.updateById(product);
            if (result > 0) {
                log.info("更新商品成功，商品ID: {}", productDTO.getId());
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("更新商品失败: {}", e.getMessage(), e);
            throw new RuntimeException("更新商品失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteProduct(Long productId) {
        try {
            int result = productMapper.deleteById(productId);
            if (result > 0) {
                log.info("删除商品成功，商品ID: {}", productId);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("删除商品失败: {}", e.getMessage(), e);
            throw new RuntimeException("删除商品失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStock(Long productId, Integer quantity) {
        try {
            int result = productMapper.updateStock(productId, quantity);
            if (result > 0) {
                log.info("更新商品库存成功，商品ID: {}, 变更数量: {}", productId, quantity);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("更新商品库存失败: {}", e.getMessage(), e);
            throw new RuntimeException("更新商品库存失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean putOnShelf(Long productId) {
        try {
            LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Product::getId, productId);

            Product product = new Product();
            product.setStatus(1); // 上架

            int result = productMapper.update(product, queryWrapper);
            if (result > 0) {
                log.info("上架商品成功，商品ID: {}", productId);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("上架商品失败: {}", e.getMessage(), e);
            throw new RuntimeException("上架商品失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean pullOffShelf(Long productId) {
        try {
            LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Product::getId, productId);

            Product product = new Product();
            product.setStatus(0); // 下架

            int result = productMapper.update(product, queryWrapper);
            if (result > 0) {
                log.info("下架商品成功，商品ID: {}", productId);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("下架商品失败: {}", e.getMessage(), e);
            throw new RuntimeException("下架商品失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean setFeatured(Long productId, Boolean featured) {
        try {
            LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Product::getId, productId);

            Product product = new Product();
            product.setIsFeatured(featured ? 1 : 0);

            int result = productMapper.update(product, queryWrapper);
            if (result > 0) {
                log.info("设置商品推荐状态成功，商品ID: {}, 推荐状态: {}", productId, featured);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("设置商品推荐状态失败: {}", e.getMessage(), e);
            throw new RuntimeException("设置商品推荐状态失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean incrementViewCount(Long productId) {
        try {
            int result = productMapper.incrementViewCount(productId);
            return result > 0;
        } catch (Exception e) {
            log.error("增加商品浏览次数失败: {}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public boolean checkProductNameExists(String productName, Long excludeId) {
        try {
            LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Product::getProductName, productName);
            if (excludeId != null) {
                queryWrapper.ne(Product::getId, excludeId);
            }
            return productMapper.selectCount(queryWrapper) > 0;
        } catch (Exception e) {
            log.error("检查商品名称是否存在失败: {}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public boolean checkProductCodeExists(String productCode, Long excludeId) {
        try {
            if (!StringUtils.hasText(productCode)) {
                return false;
            }

            LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Product::getProductCode, productCode);
            if (excludeId != null) {
                queryWrapper.ne(Product::getId, excludeId);
            }
            return productMapper.selectCount(queryWrapper) > 0;
        } catch (Exception e) {
            log.error("检查商品编码是否存在失败: {}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public ProductSimpleVO convertToSimpleVO(Product product) {
        try {
            ProductSimpleVO vo = new ProductSimpleVO();
            vo.setId(product.getId());
            vo.setProductName(product.getProductName());
            vo.setMainImage(product.getMainImage());
            vo.setPrice(product.getPrice());
            vo.setOriginalPrice(product.getOriginalPrice());
            vo.setSalesCount(product.getSalesCount());
            vo.setStockQuantity(product.getStockQuantity());
            vo.setIsFeatured(product.getIsFeatured());
            vo.setStatus(product.getStatus());

            // 计算折扣百分比
            if (product.getOriginalPrice() != null && product.getOriginalPrice().compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal discount = product.getOriginalPrice().subtract(product.getPrice());
                BigDecimal discountPercent = discount.divide(product.getOriginalPrice(), 2, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal("100"));
                vo.setDiscountPercentage(discountPercent.intValue());
            }

            // 获取分类名称
            if (product.getCategoryId() != null) {
                ProductCategory category = productCategoryService.getById(product.getCategoryId());
                if (category != null) {
                    vo.setCategoryName(category.getCategoryName());
                }
            }

            return vo;
        } catch (Exception e) {
            log.error("转换商品简单信息失败: {}", e.getMessage(), e);
            return new ProductSimpleVO();
        }
    }

    @Override
    public ProductDetailVO convertToDetailVO(Product product, Long userId) {
        try {
            ProductDetailVO vo = new ProductDetailVO();
            vo.setId(product.getId());
            vo.setProductName(product.getProductName());
            vo.setCategoryId(product.getCategoryId());
            vo.setProductCode(product.getProductCode());
            vo.setDescription(product.getDescription());
            vo.setMainImage(product.getMainImage());
            vo.setPrice(product.getPrice());
            vo.setOriginalPrice(product.getOriginalPrice());
            vo.setStockQuantity(product.getStockQuantity());
            vo.setSalesCount(product.getSalesCount());
            vo.setViewCount(product.getViewCount());
            vo.setStatus(product.getStatus());
            vo.setIsFeatured(product.getIsFeatured());

            // 格式化时间
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            vo.setCreateTime(product.getCreateTime() != null ? product.getCreateTime().format(formatter) : null);
            vo.setUpdateTime(product.getUpdateTime() != null ? product.getUpdateTime().format(formatter) : null);

            // 解析图片列表
            if (StringUtils.hasText(product.getImages())) {
                try {
                    // 使用简单的JSON解析，避免ObjectMapper依赖问题
                    ObjectMapper localMapper = new ObjectMapper();
                    List<String> imageList = localMapper.readValue(
                            product.getImages(),
                            new com.fasterxml.jackson.core.type.TypeReference<List<String>>() {}
                    );
                    vo.setImageList(imageList);
                } catch (JsonProcessingException e) {
                    log.warn("解析商品图片列表失败: {}", e.getMessage());
                    vo.setImageList(Arrays.asList(product.getMainImage()));
                }
            } else if (StringUtils.hasText(product.getMainImage())) {
                vo.setImageList(Arrays.asList(product.getMainImage()));
            }

            // 计算折扣百分比
            if (product.getOriginalPrice() != null && product.getOriginalPrice().compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal discount = product.getOriginalPrice().subtract(product.getPrice());
                BigDecimal discountPercent = discount.divide(product.getOriginalPrice(), 2, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal("100"));
                vo.setDiscountPercentage(discountPercent.intValue());
            }

            // 获取分类名称
            if (product.getCategoryId() != null) {
                ProductCategory category = productCategoryService.getById(product.getCategoryId());
                if (category != null) {
                    vo.setCategoryName(category.getCategoryName());
                }
            }

            // 检查是否已收藏
            if (userId != null) {
                vo.setIsFavorited(userFavoriteService.isFavorited(userId, product.getId()));
                vo.setFavoriteCount(userFavoriteService.countProductFavorites(product.getId()));
            }

            return vo;
        } catch (Exception e) {
            log.error("转换商品详情失败: {}", e.getMessage(), e);
            return new ProductDetailVO();
        }
    }
}
